package com.aimosheng.main.custom.videoplayerrecyclerview;

import android.content.Context;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.PagerSnapHelper;
import androidx.recyclerview.widget.RecyclerView;
import android.view.View;



public class PagerLayoutManager extends LinearLayoutManager implements RecyclerView.OnChildAttachStateChangeListener {
    private PagerSnapHelper mPagerSnapHelper = new PagerSnapHelper();
    private OnPageChangeListener mOnPageChangeListener;
    private int currentPostion;
    private boolean haveSelect;

    PagerLayoutManager(Context context) {
        super(context);
    }

    public void onAttachedToWindow(RecyclerView view) {
        view.addOnChildAttachStateChangeListener(this);
        this.mPagerSnapHelper.attachToRecyclerView(view);
        super.onAttachedToWindow(view);
    }

    public void onChildViewAttachedToWindow(@NonNull View view) {
        if (!this.haveSelect) {
            this.haveSelect = true;
            this.currentPostion = this.getPosition(view);
            this.mOnPageChangeListener.onPageSelected(this.currentPostion, view);
        }

    }

    public void onChildViewDetachedFromWindow(@NonNull View view) {
    }

    public void onScrollStateChanged(int state) {
        if (state == 0) {
            View view = this.mPagerSnapHelper.findSnapView(this);
            if (view != null && this.mOnPageChangeListener != null) {
                int position = this.getPosition(view);
                if (this.currentPostion != position) {
                    this.currentPostion = position;
                    this.mOnPageChangeListener.onPageSelected(this.currentPostion, view);
                }
            }
        }

        super.onScrollStateChanged(state);
    }

    public boolean canScrollVertically() {
        return true;
    }

    void setOnPageChangeListener(OnPageChangeListener mOnPageChangeListener) {
        this.mOnPageChangeListener = mOnPageChangeListener;
    }
}
